<?php

$start = microtime(true);


if (isset($_REQUEST['php_session_id'])) session_id($_REQUEST['php_session_id']);

session_start();




// Enable Gzip compression
if (isset($cms_config['gzip_compression']) and $cms_config['gzip_compression']) {
	ob_start("ob_gzhandler");
}

/*
 * Identify which site we're on, and redirect to primary domain
 * if we're on an alias.
 *
 */
if (isset($_SESSION['site_id'])) {
	$site = $db->fetchRow("SELECT * FROM cms_sites WHERE id=?", $_SESSION['site_id']);
} else {
	$site = $db->fetchRow("SELECT * FROM cms_sites WHERE ? REGEXP domain_regex", $_SERVER['SERVER_NAME']);
	if ($site) $_SESSION['site_id'] = $site['id'];
}
$smarty->assign('site', $site);

if (!isset($site['id'])) {
	header("HTTP/1.0 404 Not Found");
	echo "Invalid domain.\n";
	exit;
} elseif (!is_dir($app_root . $site['home_dir'])) {
	header("HTTP/1.0 404 Not Found");
	echo "Unconfigured domain.\n";
	exit;
} elseif ($_SERVER['SERVER_NAME'] != $site['domain_name'] and $site['domain_force']) {
	header("HTTP/1.0 301 Moved Permanently");
	$new_url = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $site['domain_name'] . $_SERVER['REQUEST_URI'];
	header("Location: " . $new_url);
	echo "<a href='{$new_url}'>{$new_url}</a>\n";
	exit;
}

Store::getInstance()->site = $site;

// Add site include path
ini_set('include_path', $app_root . $site['home_dir'] . '/includes:' . ini_get('include_path'));


/*
 * Split the path up into its component parts.
 *
 */
$path = explode('/', rtrim($_GET['path'], '/'));
$smarty->assign('path', $path);

/*
 * Get the environment from the database.  The table holds keys and
 * values, but we want to split the keys up on : and make a multilevel
 * array, so for instance, if the key is google:adwords:id, we would
 * have $env['google']['adwords']['id']
 *
 */
$env = array();
$result = $db->fetchAll("SELECT `key`, `value` FROM cms_environment WHERE site_id=? OR site_id=0 ORDER BY `key`, site_id", $site['id']);
foreach($result as $row) {
	$key = explode(':', $row['key']);
    $nodeRef = &$env;
    for($i=0;$i<sizeof($key);$i++) {
        if ($i == sizeof($key)-1) $nodeRef[$key[$i]] = $row['value'];
        elseif (!isset($nodeRef[$key[$i]])) $nodeRef[$key[$i]] = array();
        $nodeRef = &$nodeRef[$key[$i]];
    }
}
$smarty->assign('env', $env);

/*
 * Setup logging.
 *
 */
$logger = new Webtaculous_Log();
$logger->addWriter(new Zend_Log_Writer_Null);
if (isset($env['log'])) {
	if (isset($env['log']['file']) and $env['log']['file']) {
		$writer_file = new Zend_Log_Writer_Stream($app_root . '/logs/' . (isset($env['log']['file']['filename']) ? $env['log']['file']['filename'] : $site['domain_name'] . '.log'));
		$writer_file->addFilter(new Zend_Log_Filter_priority((int)(isset($env['log']['file']['level']) ? $env['log']['file']['level'] : 0)));
		$logger->addWriter($writer_file);
	}
	if (isset($env['log']['firebug']) and $env['log']['firebug']) {
		if (isset($env['log']['firebug']['db_profiler']) and $env['log']['firebug']['db_profiler']) {
			$profiler = new Zend_Db_Profiler_Firebug('All DB Queries');
			$profiler->setEnabled(true);
			$db->setProfiler($profiler);
		}
		if (isset($env['log']['firebug']['level']) and $env['log']['firebug']['level']) {
			$writer_firebug = new Zend_Log_Writer_Firebug();
			$writer_firebug->addFilter(new Zend_Log_Filter_priority((int)(isset($env['log']['firebug']['level']) ? $env['log']['firebug']['level'] : 7)));
			$logger->addWriter($writer_firebug);
		}
		$request = new Zend_Controller_Request_Http();
		$response = new Zend_Controller_Response_Http();
		$channel = Zend_Wildfire_Channel_HttpHeaders::getInstance();
		$channel->setRequest($request);
		$channel->setResponse($response);
		ob_start();
	}
}

/*
 * Check to see that our database is up to date, and upgrade if
 * needed.
 *
 */
$dh = opendir($app_root . '/admin/database');
$db_versions = array();
while ($file = readdir($dh)) {
	if (preg_match('/^\d+$/', $file)) {
		$db_versions[] = $file;
	}
}
sort($db_versions);
$current_version = $db->fetchOne("SELECT db_version FROM _db_version");
if ($db_versions[count($db_versions)-1] > $current_version) {
	foreach($db_versions as $db_version) {
		if ((int)basename($db_version) > $current_version) {
			$sql = file_get_contents($app_root . '/admin/database/' . $db_version);
			try {
				$db->query($sql);
				$logger->info('DBUPGRADE: ' . $sql);
			} catch(Exception $e) {
				$logger->crit('DBUPGRADE: ' . $e->getMessage());
			}
		}
	}
	$db->query("UPDATE _db_version SET db_version=?", $db_versions[count($db_versions)-1]);
	$logger->info("Updated database to version " . $db_versions[count($db_versions)-1] . ".");
}

/*
 * Ensure that we have a custom users table for this site
 *
 */
$tables = $db->fetchCol("SHOW TABLES");
if (!in_array("cms_users_custom_{$site['id']}", $tables)) {
	$db->query("CREATE TABLE cms_users_custom_{$site['id']} LIKE cms_users_custom_skel");
}

/*
 * Intercept a login attempt here, and process it.  This way, the actual login pages,
 * front end or back, already have the results available to them.  On success set
 * $_SESSION['login'].  On success or failure, set $login_succeeded.
 *
 */
require 'Password.class.php';
if (isset($_POST['login'])) {
	if (isset($_SESSION['login'])) {
		unset($_SESSION['login']);
	}
	$login_succeeded = false;
	if (isset($_POST['login']['username'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND username=?", array($site['id'], $_POST['login']['username']));
	} elseif(isset($_POST['login']['email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND email=?", array($site['id'], $_POST['login']['email']));
	} elseif(isset($_POST['login']['username_or_email'])) {
		$user = $db->fetchRow("SELECT * FROM cms_users WHERE site_id=? AND (username=? OR email=?)", array($site['id'], $_POST['login']['username_or_email'], $_POST['login']['username_or_email']));
	}
	if ($user and $user['site_id'] == $site['id'] and Password::auth($_POST['login']['password'], $user['password'])) {
		session_regenerate_id();
		$user['custom_fields'] = $db->fetchRow("SELECT * FROM cms_users_custom_{$site['id']} WHERE user_id=?", $user['id']);
		$user['access_rights'] = unserialize($user['access_rights']);
		$_SESSION['login'] = array('user' => $user, 'timestamp' => time());
		$db->update('cms_users', array('loggedin' => new Zend_Db_Expr('NOW()'), 'loggedin_ip' => $_SERVER['REMOTE_ADDR']), $db->quoteInto('id=?', $user['id']));
		$login_succeeded = true;
		unset($user);
	}
}

/*
 * Check login, and if it's valid, then set the timestamp.  If not,
 * then nuke the login.
 *
 */
if ($path[0] != 'timeout') {
	if (isset($_SESSION['login']) and time() - $_SESSION['login']['timestamp'] < (isset($env['timeout']) ? $env['timeout'] : 1800)) {
		$_SESSION['login']['timestamp'] = time();
	} else {
		unset($_SESSION['login']);
	}
}

/*
 * Set the session in in smarty as we'll need it for file uploads.
 *
 */
$smarty->assign('session_id', session_id());
